package com.none.web.service.activity.impl;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.DateUtil;
import com.none.core.common.utils.PathUtil;
import com.none.core.common.utils.ReplaceUtil;
import com.none.core.common.utils.TransactSQLInjectionUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.common.SysConstant;
import com.none.web.common.bdPush.BaiduPushUtil;
import com.none.web.model.TActivity;
import com.none.web.model.TActivityAppUser;
import com.none.web.model.TActivityImage;
import com.none.web.model.TTags;
import com.none.web.model.TUser;
import com.none.web.model.TUserApp;
import com.none.web.service.activity.IActivityService;
import com.none.web.service.comments.ICommentsService;
import com.none.web.service.logs.ILogsService;

@Service("activityService")
public class ActivityServiceImpl extends BaseServiceSupport implements IActivityService{

     @Autowired
     JdbcTemplate jdbcTemplate;
     @Autowired
 	 ILogsService logService;
     @Autowired
     ICommentsService commentsService;
	 /**
	  * pc
      * 保存活动草稿
	 * @throws Exception 
      */
	@Override
	public boolean saveDraft(TActivity activity,String startTime,String endTime,String deadline, String tags, String userId,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId)){
			throw new ValidateException("activity.userIsNull");
		}
		if (activity==null){
			return false;
		}
		if(StringUtils.isBlank(activity.getSubject())){
			throw new ValidateException("activity.subjectIsNull");
		}else{
			if(activity.getSubject().length()>100){
				throw new ValidateException("activity.subjectIsMax");
			}
		}
//		if(StringUtils.isBlank(tags)){
//			throw new ValidateException("activity.tagsIsNull");
//		}
		if(StringUtils.isNotBlank(activity.getBriefContent())){
			if(activity.getBriefContent().length()>160){
				throw new ValidateException("activity.briefContentIsMax");
			}
		}
		//判断地址不能超过200个字
		if(StringUtils.isNotBlank(activity.getVenue())){
			if(activity.getVenue().length()>200){
				throw new ValidateException("activity.venueIsMax");
			}
		}
		TUser addUser = findEntity(TUser.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		//添加用户
//		if (addUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		//设置开始结素和报名截止时间
		if(StringUtils.isNotBlank(startTime)&&!startTime.equals("NaN")){
			activity.setStartTime(new Timestamp(Long.valueOf(startTime)));
		}
		if(StringUtils.isNotBlank(endTime)&&!endTime.equals("NaN")){
			activity.setEndTime(new Timestamp(Long.valueOf(endTime)));
		}
		if(StringUtils.isNotBlank(deadline)&&!deadline.equals("NaN")){
			activity.setDeadline(new Timestamp(Long.valueOf(deadline)));
		}
		
		//甚至tags标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		if(StringUtils.isNotBlank(tags)){
			List<String> tagNames = StringUtil.split(tags, charSet);
			if (tagNames != null) {
				// 设置Tags
				Set<TTags> tages = new HashSet<TTags>();
				for (String tagName : tagNames) {
					TTags tag = null;
					Criteria tagCriteria = getCriteria(TTags.class);
					tagCriteria.add(Restrictions.eq("name", tagName));
					List<?> userList = tagCriteria.list();
					if (userList.size() > 1 || userList.size() < 0) {
						continue;
					} else if (userList.size() == 0) {
						tag = new TTags();
						tag.setTagId(CreateID.getID());
						tag.setName(tagName);
					} else if (userList.size() == 1) {
						tag = (TTags) userList.get(0);
					}
					tages.add(tag);
				}
				activity.setTags(tages);
			}
		}

		TActivity acti = null;
		activity.setEditUser(addUser);
		//添加保存时间等
		activity.setEditTime(new Timestamp(new Date().getTime()));
		
        if(StringUtils.isNotBlank(activity.getId())){
    		//判断用户权限
			acti = findEntity(TActivity.class, activity.getId());
			if(acti==null){
				throw new ValidateException("activity.activityUnExist");
			}
			TActivity activity_this = acti;
			 //activity_this = findEntity(TActivity.class, activity.getId());
			//审核者,只可以操作同部门信息以及非别人的草稿
			if("reviewer".equals(addUser.getUserType())){
				if(activity_this!=null){
					TUser tuser=activity_this.getCreateUser();
					if(tuser!=null){
						if(tuser.getBranch()!=null){
							//1.判断是否同部门活动信息
							if(!tuser.getBranch().equals(addUser.getBranch())){
								throw new ValidateException("activity.deptError");
							}
							//2.判断是否时别人的草稿
							if(activity_this.getStatus()==0){
								if(!userId.equals(tuser.getUserId())){
									throw new ValidateException("activity.deptError");
								}
							}
						}
					}
				}
			}
			//发布者，只可以改自己的草稿
			if("reporter".equals(addUser.getUserType())){
				//只能添加，修改保存草稿草稿
				if(activity_this!=null){
					if(activity_this.getStatus()!=0&&activity_this.getStatus()!=-1&&activity_this.getStatus()!=2){
						throw new ValidateException("activity.deptError");
					}
				}
			}
			if(activity.getStatus().intValue()==0){
				//设置活动信息为草稿
				acti.setStatus(0);
			}else if(activity.getStatus().intValue()==1){
				acti.setStatus(1);
				acti.setSubmit_time(new Timestamp(new Date().getTime()));
				acti.setSubmit_user_id(userId);
			}else if(activity.getStatus().intValue()==2){
				acti.setStatus(2);
				acti.setReviewUser(addUser);
				acti.setReviewTime(new Timestamp(new Date().getTime()));
				acti.setSubmit_time(new Timestamp(new Date().getTime()));
				acti.setSubmit_user_id(userId);
			}
        	acti.setTags(activity.getTags());
        	acti.setBanner(activity.getBanner());
        	acti.setBriefContent(activity.getBriefContent());
        	acti.setDeadline(activity.getDeadline());
        	if(StringUtils.isNotBlank(activity.getDescription())){
        		acti.setDescription(ReplaceUtil.replaceSomeString(activity.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
        	}
        	
        	acti.setEditTime(activity.getEditTime());
        	acti.setEditUser(activity.getEditUser());
        	//acti.setEndTime(activity.getEndTime());
        	acti.setEnroll_need(activity.getEnroll_need());
        	acti.setJoinType(activity.getJoinType());
        	acti.setLimitNum(activity.getLimitNum());
        	//acti.setStartTime(activity.getStartTime());
        	acti.setSubject(activity.getSubject());
        	acti.setVenue(activity.getVenue());
        	if(acti.getPush_count()==null){
        		acti.setPush_count(0);
        	}
        	if(push==null||"".equals(push)){
        		acti.setPush("no");
        	}else{
        		acti.setPush(push);
        	}
        	
        	//推送
			if(acti.getStatus()==2){
				if("push".equals(push)&&acti.getPush_count()==0){//是否push
					//this.push_bd(acti.getSubject(), acti.getBriefContent(), "ios", null,"activity", acti.getId());
					//this.push_bd(acti.getSubject(), acti.getBriefContent(), "android", null, "activity", acti.getId());
					BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"activity", acti.getId());
					BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "activity", acti.getId());
					Integer push_count=0;
					if(acti.getPush_count()!=null){
						push_count=acti.getPush_count();
					}
					acti.setPush_count(push_count+1);
				}
			}
			acti.setPushInfo(pushcontent);
			updateEntity(acti);
			//delete image list
			String delSql="delete from t_activity_image where activity_id='"+acti.getId()+"'";
			this.jdbcTemplate.execute(delSql);
			//save image list
			if(activity.getImageList()!=null && activity.getImageList().size()>0){
				for (int i = 0; i < activity.getImageList().size(); i++) {
					TActivityImage image = activity.getImageList().get(i);
					image.setActivityId(acti.getId());
					if (saveEntity(image) == null) {
							throw new ValidateException("common.illegalRequest");
					}
				}
			}
		}else{
			if(activity.getStatus().intValue()==0){
				//设置活动信息为草稿
				activity.setStatus(0);
			}else if(activity.getStatus().intValue()==1){
				activity.setStatus(1);
				activity.setSubmit_time(new Timestamp(new Date().getTime()));
				activity.setSubmit_user_id(userId);
			}else if(activity.getStatus().intValue()==2){
				activity.setStatus(2);
				activity.setReviewUser(addUser);
				activity.setReviewTime(new Timestamp(new Date().getTime()));
				activity.setSubmit_time(new Timestamp(new Date().getTime()));
				activity.setSubmit_user_id(userId);
			}

			activity.setCreateUser(addUser);
			activity.setCreateTime(new Timestamp(new Date().getTime()));
			activity.setEditUser(addUser);
			activity.setEditTime(new Timestamp(new Date().getTime()));
			activity.setPush_count(0);
			if(push==null||"".equals(push)){
				activity.setPush("no");
        	}else{
        		activity.setPush(push);
        	}
			//ID
			String id = CreateID.getID();
			activity.setId(id);
			
			//推送
			if(activity.getStatus()==2){
				if("push".equals(push)&&activity.getPush_count()==0){//是否push
					//this.push_bd(activity.getSubject(), activity.getBriefContent(), "ios", null,"activity", activity.getId());
					//this.push_bd(activity.getSubject(), activity.getBriefContent(), "android", null, "activity", activity.getId());
					BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"activity", activity.getId());
					BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "activity", activity.getId());
					Integer push_count=0;
					if(activity.getPush_count()!=null){
						push_count=activity.getPush_count();
					}
					activity.setPush_count(push_count+1);
				}
			}
			//save image list
			if(activity.getImageList()!=null && activity.getImageList().size()>0){
				for (int i = 0; i < activity.getImageList().size(); i++) {
					TActivityImage image = activity.getImageList().get(i);
					image.setActivityId(activity.getId());
					if (saveEntity(image) == null) {
							throw new ValidateException("common.illegalRequest");
					}
				}
			}
			if(StringUtils.isNotBlank(activity.getDescription())){
				activity.setDescription(ReplaceUtil.replaceSomeString(activity.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
			}
			// 保存
			activity.setPushInfo(pushcontent);
			if (saveEntity(activity) == null) {
					throw new ValidateException("common.illegalRequest");
			}
		}
		return true;
	}

	/**
	 * pc
     * 创建活动
	 * @throws Exception 
     */
	@Override
	public boolean createActivity(TActivity activity,String startTime,String endTime,String deadline, String tags, String userId,String push,HttpServletRequest request,String pushcontent) throws Exception{
		
		if (StringUtils.isBlank(userId)){
			throw new ValidateException("activity.userIsNull");
		}
		if (activity==null){
			return false;
		}
		if(StringUtils.isBlank(activity.getSubject())){
			throw new ValidateException("activity.subjectIsNull");
		}
		if(StringUtils.isNotBlank(activity.getBriefContent())){
			if(activity.getBriefContent().length()>160){
				throw new ValidateException("activity.briefContentIsMax");
			}
		}
		//判断地址不能超过200个字
		if(StringUtils.isNotBlank(activity.getVenue())){
			if(activity.getVenue().length()>200){
				throw new ValidateException("activity.venueIsMax");
			}
		}
		if(StringUtils.isBlank(tags)){
			throw new ValidateException("activity.tagsIsNull");
		}
		
		//ID
		String id = CreateID.getID();
		activity.setId(id);
		activity.setPush_count(0);
		if(push==null||"".equals(push)){
			activity.setPush("no");
    	}else{
    		activity.setPush(push);
    	}
		//添加用户
		TUser addUser = findEntity(TUser.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}
//		if (addUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		
		//设置活动信息为待审核
		// 审核者保存为审核通过
		if("reviewer".equals(addUser.getUserType())){
			activity.setStatus(2);
			activity.setReviewUser(addUser);
			activity.setReviewTime(new Timestamp(new Date().getTime()));
			activity.setSubmit_time(new Timestamp(new Date().getTime()));
			activity.setSubmit_user_id(userId);
		}
		//发布者，保存为等待审核
		if("reporter".equals(addUser.getUserType())){
			activity.setStatus(1);
			activity.setSubmit_time(new Timestamp(new Date().getTime()));
			activity.setSubmit_time(new Timestamp(new Date().getTime()));
			activity.setSubmit_user_id(userId);
		}
		activity.setCreateUser(addUser);
		activity.setEditUser(addUser);
		//添加保存时间等
		activity.setEditTime(new Timestamp(new Date().getTime()));
		activity.setCreateTime(new Timestamp(new Date().getTime()));
		//设置开始结素和报名截止时间
		if(StringUtils.isNotBlank(startTime)&&!startTime.equals("NaN")){
			activity.setStartTime(new Timestamp(Long.valueOf(startTime)));
		}
		if(StringUtils.isNotBlank(endTime)&&!endTime.equals("NaN")){
			activity.setEndTime(new Timestamp(Long.valueOf(endTime)));
		}
		if(StringUtils.isNotBlank(deadline)&&!deadline.equals("NaN")){
			activity.setDeadline(new Timestamp(Long.valueOf(deadline)));
		}
		//甚至tags标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		List<String> tagNames = StringUtil.split(tags, charSet);
		if (tagNames != null) {
			// 设置Tags
			Set<TTags> tages = new HashSet<TTags>();
			for (String tagName : tagNames) {
				TTags tag = null;
				Criteria tagCriteria = getCriteria(TTags.class);
				tagCriteria.add(Restrictions.eq("name", tagName));
				List<?> userList = tagCriteria.list();
				if (userList.size() > 1 || userList.size() < 0) {
					continue;
				} else if (userList.size() == 0) {
					tag = new TTags();
					tag.setTagId(CreateID.getID());
					tag.setName(tagName);
				} else if (userList.size() == 1) {
					tag = (TTags) userList.get(0);
				}
				tages.add(tag);
			}
			activity.setTags(tages);
		}
		if(StringUtils.isNotBlank(activity.getDescription())){
			activity.setDescription(ReplaceUtil.replaceSomeString(activity.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		}
		// 保存
		activity.setPushInfo(pushcontent);
		//推送
		if(activity.getStatus()==2){
			if("push".equals(push)&&activity.getPush_count()==0){//是否push
				//this.push_bd(activity.getSubject(), activity.getBriefContent(), "ios", null,"activity", activity.getId());
				//this.push_bd(activity.getSubject(), activity.getBriefContent(), "android", null, "activity", activity.getId());
				BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"activity", activity.getId());
				BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "activity", activity.getId());
				Integer push_count=0;
				if(activity.getPush_count()!=null){
					push_count=activity.getPush_count();
				}
				activity.setPush_count(push_count+1);
				//updateEntity(activity);
			}
		}
		if (saveEntity(activity) == null) {
				throw new ValidateException("common.illegalRequest");
		}
		
		return true;
	}

	/**
	 * PC
	 * 修改活动  
	 * @author Bing  
	 * @times  2014-11-07
	 * @param  activity 
	 * 		   tags
	 *         userId
	 * return 修改后的活动
	 */
	@Override
	public Object editActivity(TActivity activity,String startTime,String endTime,String deadline, String tags, String userId,String push,HttpServletRequest request,String pushcontent) throws Exception{
		if (StringUtils.isBlank(userId)){
			throw new ValidateException("activity.userIsNull");
		}
		if (activity==null){
			return false;
		}
		if(StringUtils.isBlank(activity.getId())){
			return false;
		}
		TActivity act = findEntity(TActivity.class, activity.getId());
		if(StringUtils.isBlank(activity.getSubject())){
			throw new ValidateException("activity.subjectIsNull");
		}
		if(0!=act.getStatus()){
			if(StringUtils.isBlank(tags)){
				throw new ValidateException("activity.tagsIsNull");
			}
		}
		if(StringUtils.isNotBlank(activity.getBriefContent())){
			if(activity.getBriefContent().length()>160){
				throw new ValidateException("activity.briefContentIsMax");
			}
		}
		//判断地址不能超过200个字
		if(StringUtils.isNotBlank(activity.getVenue())){
			if(activity.getVenue().length()>200){
				throw new ValidateException("activity.venueIsMax");
			}
		}		
		
		
		//添加用户
		TUser addUser = findEntity(TUser.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}
//		if (addUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		TActivity acti = findEntity(TActivity.class, activity.getId());
		// 不同用户类型
		if(StringUtils.isNotBlank(activity.getId())){
			if(acti==null){
				throw new ValidateException("activity.activityUnExist");
			}
			TActivity activity_this = acti;
			//审核者,只可以操作同部门信息以及非别人的草稿
			if("reviewer".equals(addUser.getUserType())){
				if(activity_this!=null){
					TUser tuser=activity_this.getCreateUser();
					if(tuser!=null){
						if(tuser.getBranch()!=null){
							//1.判断是否同部门活动信息
							if(!tuser.getBranch().equals(addUser.getBranch())){
								throw new ValidateException("activity.deptError");
							}
							//2.判断是否时别人的草稿
//							if(activity_this.getStatus()==0){
//								if(!userId.equals(tuser.getUserId())){
//									throw new ValidateException("common.illegalRequest");
//								}
//							}
						}
					}
				}
			}
			//发布者，只可以改自己的草稿，和被拒绝的活动
			if("reporter".equals(addUser.getUserType())){
				//只能添加，修改保存草稿草稿
				if(activity_this!=null){
					if(activity_this.getStatus()!=0&&activity_this.getStatus()!=-1&&activity_this.getStatus()!=2){
						throw new ValidateException("activity.deptError");
					}
					
					if(!activity_this.getCreateUser().getUserId().equals(userId)){
						throw new ValidateException("activity.deptError");
					}
				}
			}
		}
		
		
		act.setEditUser(addUser);
		//添加保存时间等
		act.setEditTime(new Timestamp(new Date().getTime()));
		//设置开始结素和报名截止时间
//		if(StringUtils.isNotBlank(startTime)){
//			act.setStartTime(new Timestamp(Long.valueOf(startTime)));
//		}
//		if(StringUtils.isNotBlank(endTime)){
//			act.setEndTime(new Timestamp(Long.valueOf(endTime)));
//		}
//		if(StringUtils.isNotBlank(deadline)){
//			act.setDeadline(new Timestamp(Long.valueOf(deadline)));
//		}
		
		//设置开始结素和报名截止时间
		if(StringUtils.isNotBlank(startTime)&&!startTime.equals("NaN")){
			act.setStartTime(new Timestamp(Long.valueOf(startTime)));
		}
		if(StringUtils.isNotBlank(endTime)&&!endTime.equals("NaN")){
			act.setEndTime(new Timestamp(Long.valueOf(endTime)));
		}
		if(StringUtils.isNotBlank(deadline)&&!deadline.equals("NaN")){
			act.setDeadline(new Timestamp(Long.valueOf(deadline)));
		}
		//甚至tags标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		List<String> tagNames = StringUtil.split(tags, charSet);
		if (tagNames != null) {
			// 设置Tags
			Set<TTags> tages = new HashSet<TTags>();
			for (String tagName : tagNames) {
				TTags tag = null;
				Criteria tagCriteria = getCriteria(TTags.class);
				tagCriteria.add(Restrictions.eq("name", tagName));
				List<?> userList = tagCriteria.list();
				if (userList.size() > 1 || userList.size() < 0) {
					continue;
				} else if (userList.size() == 0) {
					tag = new TTags();
					tag.setTagId(CreateID.getID());
					tag.setName(tagName);
				} else if (userList.size() == 1) {
					tag = (TTags) userList.get(0);
				}
				tages.add(tag);
			}
			act.setTags(tages);
		}
		// 保存
		//activity.setStatus(acti.getStatus());
		if(activity.getStatus().intValue()==0){
			//设置活动信息为草稿
			act.setStatus(0);
			act.setReviewUser(acti.getReviewUser());
			act.setReviewTime(acti.getReviewTime());
		}else if(activity.getStatus().intValue()==1){
			act.setStatus(1);
			act.setSubmit_time(new Timestamp(new Date().getTime()));
			act.setSubmit_user_id(userId);
		}else if(activity.getStatus().intValue()==2){
			act.setStatus(2);
			act.setReviewUser(addUser);
			act.setReviewTime(new Timestamp(new Date().getTime()));
			act.setSubmit_time(new Timestamp(new Date().getTime()));
			act.setSubmit_user_id(userId);
		}
		act.setCreateUser(acti.getCreateUser());
		act.setCreateTime(acti.getCreateTime());
		act.setPush(push);
		//act.setCreateUser(acti.getCreateUser());
		//act.setCreateTime(acti.getCreateTime());
		if(act.getPush_count()==null){
			act.setPush_count(0);
    	}
		if(push==null||"".equals(push)){
			act.setPush("no");
    	}else{
    		act.setPush(push);
    	}
		//推送
		if(activity.getStatus()==2){
			if("push".equals(push)&&act.getPush_count()==0){//是否push
				//this.push_bd(activity.getSubject(), activity.getBriefContent(), "ios", null,"activity", activity.getId());
				//this.push_bd(activity.getSubject(), activity.getBriefContent(), "android", null, "activity", activity.getId());
				BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"activity", activity.getId());
				BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "activity", activity.getId());
				Integer push_count=0;
				if(activity.getPush_count()!=null){
					push_count=activity.getPush_count();
				}
				act.setPush_count(push_count+1);
			}
		}
		if(StringUtils.isNotBlank(act.getDescription())){
			act.setDescription(ReplaceUtil.replaceSomeString(act.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
		}
		act.setPushInfo(pushcontent);
		
		//act.setEndTime(activity.getEndTime());
		act.setEnroll_need(activity.getEnroll_need());
		act.setJoinType(activity.getJoinType());
		act.setLimitNum(activity.getLimitNum());
		//act.setStartTime(activity.getStartTime());
		act.setSubject(activity.getSubject());
		act.setVenue(activity.getVenue());
		updateObj(act);
		return true;
	}

	/**
	 * pc
     * 删除活动
     * @author Bing  
	 * @times  2014-11-07
	 * @param  activityId 活动ID
     * return  list
     */
	@SuppressWarnings("unused")
	@Override
	public boolean deleteActivity(String activityId,String userId) throws Exception{
		if (StringUtils.isBlank(userId))
			throw new ValidateException("activity.updateUserNull");

		TActivity tActivity = null;
		TUser loginUser = findEntity(TUser.class, userId);
		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		/*
		 * 判断是reviewer（审核者）还是reporter（发布者）
		 * reviewer除了别人的草稿，身下自己部门的所有活动和自己的草稿活动都可以删除
		 * reporter用户只可以删除自己的草稿
		 */
        //start
		if (StringUtils.isNotBlank(activityId)) {
			tActivity = findEntity(TActivity.class, activityId);
			if(tActivity==null){
				throw new ValidateException("activity.activityUnExist");
			}
			TUser createUser=tActivity.getCreateUser();
			if (tActivity != null) {
//				if("reviewer".equals(loginUser.getUserType())){
//					//判断活动是不是自己部门发布的
//					if(createUser!=null){
//						if(loginUser.getBranch().equals(createUser.getBranch())){
//							//如果是别人的草稿
//							if("0".equals(tActivity.getStatus())){
//								if(!createUser.getUserId().equals(loginUser.getUserId())){
//									//不是 自己的草稿，异常回馈
//									throw new ValidateException("activity.authorError");
//								}
//							}
//						}else{
//							//不是同一个部门的，异常回馈
//							throw new ValidateException("activity.deptError");
//						}
//					}
//				}else 
				if("reporter".equals(loginUser.getUserType())){
					if("0".equals(tActivity.getStatus().toString())){
						if(!createUser.getUserId().equals(loginUser.getUserId())){
							//只能删除自己的草稿，异常回馈
							throw new ValidateException("activity.authorError");
						}
					}else{
						//reporter用户只能删除草稿，异常回馈
						throw new ValidateException("activity.isDeleteDraft");
					}
				}
				//end
			}else{
				throw new ValidateException("activity.activityNoExist");
			}
		}else{
		    return 	false;
		}
		boolean flag=deleteEntity(tActivity);
		//活动删除成功后，删除与该活动相关的其他信息
		if(flag){
			String delSql="delete from t_activity_appuser where activity_id='"+activityId+"'";
			this.jdbcTemplate.execute(delSql);
		}
		return flag;
	}

	/**
	 * pc
     * 等待审核的活动
     * @author Bing  
	 * @times  2014-11-07
     * return  list
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object listPending_review(Pager pager, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("activity.unLogin");
		// 得到审批者的信息
		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("activity.pedingNotRight");
		}
		Criteria criteria = getCriteria(TActivity.class);
		criteria.add(Restrictions.eq("status", 1));//状态为待审核的数据

		criteria.createAlias("createUser", "cru");
		criteria.add(Restrictions.eq("cru.branch", loginUser.getBranch()));

		criteria.addOrder(Order.desc("createTime"));

		List<TActivity> list = new ArrayList<TActivity>();
		
		List<TActivity> reslist = (List<TActivity>)listQBC(criteria);
		for (Iterator iterator = reslist.iterator(); iterator.hasNext();) {
			TActivity tActivity = (TActivity) iterator.next();
			
			//add by Bing 2015-08-05
			Set<TTags> tagset = tActivity.getTags();
			Iterator it=tagset.iterator();
			String haveNowTagFlag="noNowTag";
				
			while(it .hasNext() ){
				TTags tag=(TTags) it.next();
				if("NOW".equals(tag.getName())){
					haveNowTagFlag="haveNowTag";
					break;
				}
			}
			tActivity.setHaveNowTagFlag(haveNowTagFlag);

			//add by william 2014-12-11
			Criteria activityImageCriteria = getCriteria(TActivityImage.class);
			activityImageCriteria.add(Restrictions.eq("activityId", tActivity.getId()));
			activityImageCriteria.addOrder(Order.asc("orderIndex"));
			tActivity.setImageList(activityImageCriteria.list());
			
			tActivity.setFlag(this.checkActivity(tActivity.getId(), userId));
			
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tActivity.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tActivity.setLike(true);
			}else{
				tActivity.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			tActivity.setBrowseTimes(logService.getBrowseTimes(tActivity.getId(), "activity", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(tActivity.getId(), "activity", userId));
			
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+tActivity.getId()+"' order by t.publish_time desc";
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					
//					//Console Admin角色可以删除评论
//					if (loginUser.getRole().indexOf("Console Admin") == -1) {
//						comment.setCanDelete(false);
//					}else{
//						comment.setCanDelete(true);
//					}
//					
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tActivity.setCommentList(commentList);
//			}
//			
//			//设置评论数量  Add by Bing 2015-07-07
//			tActivity.setCommentAmount(commentList.size());
			
			list.add(tActivity);
		}
		return list;
	}

	/**
	 * pc
     * 审核活动---通过
     * @author Bing  
	 * @times  2014-11-07
     */
	@Override
	public Object review(TActivity activity,String startTime,String endTime,String deadline, String tags, String userId,String push,HttpServletRequest request,String pushcontent) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("activity.approvalUserNull");

		if (activity.getId() == null) {
			throw new ValidateException("activity.activityIdIsNull");
		}

		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}
		/*if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("activity.pedingNotRight");
		}*/
		TActivity tActivity =null;
		if (StringUtils.isNotBlank(activity.getId())) {
			tActivity = findEntity(TActivity.class, activity.getId());
			if (tActivity != null) {
				if("reporter".equals(loginUser.getUserType())){
					//只能添加，修改保存草稿草稿
					if(tActivity!=null){
						if(!tActivity.getCreateUser().getUserId().equals(userId)){
							throw new ValidateException("activity.pedingNotRight");
						}
					}
				}
//				if (tActivity.getStatus()==2) {
//					throw new ValidateException("activity.publishedNotUpdate");
//				}
				//重新赋值
				if (StringUtils.isNotBlank(activity.getSubject())) {
					tActivity.setSubject(activity.getSubject());
				}
				if (StringUtils.isNotBlank(activity.getVenue())) {
					if(activity.getVenue().length()>200){
						throw new ValidateException("activity.venueIsMax");
					}
					tActivity.setVenue(activity.getVenue());
				}
				if (StringUtils.isNotBlank(activity.getBanner())) {
					tActivity.setBanner(activity.getBanner());
				}
				
				if (StringUtils.isNotBlank(activity.getBriefContent())) {
					if(activity.getBriefContent().length()>160){
						throw new ValidateException("activity.briefContentIsMax");
					}
					tActivity.setBriefContent(activity.getBriefContent());
				}
				
				if (StringUtils.isNotBlank(activity.getDescription())) {
					tActivity.setDescription(activity.getDescription());
				}
				if (StringUtils.isNotBlank(String.valueOf(activity.getLimitNum()))) {
					tActivity.setLimitNum(activity.getLimitNum());
				}
				
				if (StringUtils.isNotBlank(String.valueOf(activity.getJoinType()))) {
					tActivity.setJoinType(activity.getJoinType());
				}
			
				//if (StringUtils.isNotBlank(activity.getDeadline().toString())) {
				//	tActivity.setDeadline(activity.getDeadline());
				//}
				tActivity.setDeadline(activity.getDeadline());
				
				tActivity.setPush(push);
				
				if (StringUtils.isNotBlank(tags)) {
					String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };

					List<String> tagNames = StringUtil.split(tags, charSet);
					if (tagNames != null) {
						// 设置Tags
						Set<TTags> tages = new HashSet<TTags>();
						for (String tagName : tagNames) {
							TTags tag = null;
							Criteria tagCriteria = getCriteria(TTags.class);
							tagCriteria.add(Restrictions.eq("name", tagName));
							// tagCriteria.add(Restrictions.eq("name",
							// tagName));
							List<?> userList = tagCriteria.list();
							if (userList.size() > 1 || userList.size() < 0) {
								// new ValidateException("common.sysException");
								continue;
							} else if (userList.size() == 0) {
								tag = new TTags();
								tag.setTagId(CreateID.getID());
								tag.setName(tagName);
							} else if (userList.size() == 1) {
								tag = (TTags) userList.get(0);
							}
	
							tages.add(tag);
						}
						tActivity.getTags().removeAll(tActivity.getTags());
						tActivity.setTags(tages);
					}
				}
				// 设置修改人员
				tActivity.setEditUser(loginUser);
				// 设置修改时间
				tActivity.setEditTime(new Timestamp(new Date().getTime()));
				// 设置活动状态为2（审核通过）
//				if (!"reviewer".equals(loginUser.getUserType())) {
//					tActivity.setStatus(1);
//				}else{
//					tActivity.setStatus(2);
//				}
				if(activity.getStatus().intValue()==0){
					//设置活动信息为草稿
					tActivity.setStatus(0);
				}else if(activity.getStatus().intValue()==1){
					tActivity.setStatus(1);
					tActivity.setSubmit_time(new Timestamp(new Date().getTime()));
					tActivity.setSubmit_user_id(userId);
				}else if(activity.getStatus().intValue()==2){
					tActivity.setStatus(2);
					tActivity.setReviewUser(loginUser);
					tActivity.setReviewTime(new Timestamp(new Date().getTime()));
					tActivity.setSubmit_time(new Timestamp(new Date().getTime()));
					tActivity.setSubmit_user_id(userId);
				}
//				tActivity.setReviewUser(loginUser);
				//设置开始结素和报名截止时间
				if(StringUtils.isNotBlank(startTime)&&!startTime.equals("NaN")){
					tActivity.setStartTime(new Timestamp(Long.valueOf(startTime)));
				}
				if(StringUtils.isNotBlank(endTime)&&!endTime.equals("NaN")){
					tActivity.setEndTime(new Timestamp(Long.valueOf(endTime)));
				}
				if(StringUtils.isNotBlank(deadline)&&!deadline.equals("NaN")){
					tActivity.setDeadline(new Timestamp(Long.valueOf(deadline)));
				}
				// 设置审批时间
				tActivity.setReviewTime(new Timestamp(new Date().getTime()));
				if(tActivity.getPush_count()==null){
					tActivity.setPush_count(0);
				}
				if(push==null||"".equals(push)){
					tActivity.setPush("no");
		    	}else{
		    		tActivity.setPush(push);
		    	}
				//推送
				if(tActivity.getStatus()==2){
					if("push".equals(push)&&tActivity.getPush_count()==0){//是否push
						//this.push_bd(tActivity.getSubject(), tActivity.getBriefContent(), "ios", null,"activity", tActivity.getId());
						//this.push_bd(tActivity.getSubject(), tActivity.getBriefContent(), "android", null, "activity", tActivity.getId());
						BaiduPushUtil.push_bd(pushcontent, "", "ios", null,"activity", tActivity.getId());
						BaiduPushUtil.push_bd(pushcontent, " ", "android", null, "activity", tActivity.getId());
						Integer push_count=0;
						if(tActivity.getPush_count()!=null){
							push_count=tActivity.getPush_count();
						}
						tActivity.setPush_count(push_count+1);
					}
				}
				if(StringUtils.isNotBlank(tActivity.getDescription())){
					tActivity.setDescription(ReplaceUtil.replaceSomeString(tActivity.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
				}
				tActivity.setPushInfo(pushcontent);
				
				//tActivity.setEndTime(activity.getEndTime());
				tActivity.setEnroll_need(activity.getEnroll_need());
				tActivity.setJoinType(activity.getJoinType());
				tActivity.setLimitNum(activity.getLimitNum());
				//tActivity.setStartTime(activity.getStartTime());
				tActivity.setSubject(activity.getSubject());
				tActivity.setVenue(activity.getVenue());
				updateEntity(tActivity);
				
			}
		}

		if (tActivity != null) {
			return tActivity;
		} else {
			throw new ValidateException("activity.activityNoExist");
		}
	}

	/**
	 * pc
     * 审核活动---拒绝
     * @author Bing  
	 * @times  2014-11-07
     */
	@Override
	public Object reject(String activityId,String userId,HttpServletRequest request) throws Exception{
		if (StringUtils.isBlank(userId))
			throw new ValidateException("activity.approvalUserNull");

		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (loginUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

		if (!"reviewer".equals(loginUser.getUserType())) {
			throw new ValidateException("activity.pedingNotRight");
		}
		TActivity tActivity = null;
		if (StringUtils.isNotBlank(activityId)) {
			tActivity = findEntity(TActivity.class, activityId);
			if (tActivity != null) {
				//设置活动状态为-1（拒绝）
				tActivity.setStatus(-1);
				tActivity.setReviewUser(loginUser);
				// 设置审批时间
				tActivity.setReviewTime(new Timestamp(new Date().getTime()));
				if(StringUtils.isNotBlank(tActivity.getDescription())){
					tActivity.setDescription(ReplaceUtil.replaceSomeString(tActivity.getDescription(), "src=\"/freemarker/upload", "src=\""+PathUtil.getServerPath(request)+"/freemarker/upload"));
				}
				updateEntity(tActivity);
			}
		}
		if (tActivity != null) {
			return tActivity;
		} else {
			throw new ValidateException("activity.activityNoExist");
		}
	}

	/**
	 * pc
     * 搜索活动
     * @author Bing  
	 * @times  2014-11-07
     * list
     */
	@SuppressWarnings({ "unchecked" })
	@Override
	public Object search(Pager pager, String keyword, String startTime,
			String endTime, String tags,String userId,String status) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 分割tag标签
		TUser listUser = findEntity(TUser.class, userId);
		if (listUser == null) {
			throw new ValidateException("user.userUnExist");
		}

//		if (listUser.getRole().indexOf("Content user") == -1) {
//			throw new ValidateException("user.userIsNotRole");
//		}

//		Criteria criteria = getCriteria(TActivity.class);
//		criteria.createAlias("createUser", "addUser");
		//criteria.createAlias("editUser", "up");
		//criteria.createAlias("reviewUser", "app");
		//登录用户是审核者，可以搜索出同部门人活动，除了别人的草稿。
//		if("reviewer".equals(listUser.getUserType())){
//			criteria.add(Restrictions.eq("addUser.branch", listUser.getBranch()));
//			criteria.add(Restrictions.or(Restrictions.eq("addUser.userId", userId),Restrictions.and(
//					          Restrictions.not(Restrictions.eq("addUser.userId", userId)),
//					          Restrictions.not(Restrictions.eq("status", 0)))));
			//criteria.add(Restrictions.or(
			//		Restrictions.and(Restrictions.eq("addUser.branch", listUser.getBranch()),Restrictions.ne("status", 0)),//同部门的非草稿消息
			//		Restrictions.and(Restrictions.eq("addUser.userId", listUser.getUserId()),Restrictions.eq("status", 0)),//自己的草稿
			//		Restrictions.and(Restrictions.eq("up.userId", listUser.getUserId()),Restrictions.eq("status", 0))));//审核通过后再编辑后别人的草稿
		// 登录用户是发布者，只能搜索出自己发的活动。
//		}else if ("reporter".equals(listUser.getUserType())){
//			criteria.add(Restrictions.eq("addUser.userId", userId));
			
			//criteria.add(Restrictions.eq("addUser.userId", listUser.getUserId()));
			//criteria.add(Restrictions.isNull("app.userId"));
//		}else{
//			throw new ValidateException("user.userUnExist");
//		}
        
        //输入的搜索条件
//		if (StringUtils.isNotBlank(keyword)) {
//			criteria.add(Restrictions.or(Restrictions.like("subject", "%" + keyword + "%"),
//					Restrictions.eq("id", keyword),Restrictions.like("briefContent", "%" + keyword + "%")));
//		}
//		if (StringUtils.isNotBlank(tags)) {
//			String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
//			List<String> tagNames = StringUtil.split(tags, charSet);
//			Criteria tagCriteria = getCriteria(TTags.class);
//
//			tagCriteria.add(Restrictions.in("name", tagNames));
//			List<TTags> tTagsList = tagCriteria.list();
//			List<String> activityIdList = new ArrayList<String>();
//			for (TTags tTags : tTagsList) {
//				for (TActivity activity : tTags.getActivitys()) {
//					activityIdList.add(activity.getId());
//				}
//			}
//			if (activityIdList.size() > 0) {
//				criteria.add(Restrictions.in("id", activityIdList));
//			}else{
//				return new ArrayList<TActivity>();
//			}
//		}
//		if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
//			criteria.add(Restrictions.between("createTime", this.updateDate(this.getDate(startTime), "start"), this.updateDate(this.getDate(endTime), "end")));
//		} else if (StringUtils.isNotBlank(startTime)) {
//			criteria.add(Restrictions.ge("createTime", this.updateDate(this.getDate(startTime), "start")));
//		} else if (StringUtils.isNotBlank(endTime)) {
//			criteria.add(Restrictions.le("createTime", this.updateDate(this.getDate(startTime), "start")));
//		}
//
//		criteria.addOrder(Order.desc("createTime"));
//		if(StringUtils.isNotBlank(status)){
//			criteria.add(Restrictions.eq("status",  Integer.parseInt(status)));
//		}
		
		
		
		
		List<TActivity> tlist = new ArrayList<TActivity>();
		
		boolean bool = TransactSQLInjectionUtil.sql_inj(StringUtil.toString(keyword)); //防止SQL注入
		if(bool){
			return tlist;
		}else{
			StringBuffer sql = new StringBuffer();
			sql.append("select t.* from t_activity t");
			sql.append(" left join t_user app on t.review_userid = app.user_id");
			sql.append(" left join t_user au on t.create_userid = au.user_id");
			
			if ("reviewer".equals(listUser.getUserType())) {
				sql.append(" left join t_user up on t.edit_userid = up.user_id");
				sql.append(" where au.branch ='"+listUser.getBranch()+"'");
				
				sql.append(" and !(");
				sql.append(" (");
				sql.append(" t. status =0");
				sql.append(" and t.create_userid <>'"+userId+"'");
				sql.append(" and t.review_userid is null");
				sql.append(" )");
				sql.append(" or (");
				sql.append(" t. status =0");
				sql.append(" and t.edit_userid <>'"+userId+"'");
				sql.append(" and t.review_userid is not null");
				sql.append(" )");
				sql.append(" )");
			} else {
				sql.append(" left join t_user up on t.edit_userid = up.user_id");
				sql.append(" where t.create_userid ='"+userId+"'");
				sql.append(" and !(t. status =0 and t.review_userid is not null and  t.edit_userid <>'"+userId+"')");
			}
			
			if (StringUtils.isNotBlank(keyword)) {
				sql.append(" and (t.subject like '%"+keyword+"%' or t.brief_content like '%"+keyword+"%')");
			}
			
			if (StringUtils.isNotBlank(tags)) {
				// 分割tag标签
				String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
				List<String> tagNames = StringUtil.split(tags, charSet);
				String tagNameStr="";
				for(int i=0;i<tagNames.size();i++){
					tagNameStr+="'"+StringUtil.toString(tagNames.get(i))+"',";
				}
				String tagSql = "select t.tag_id from t_tags t where t.name in("+tagNameStr.substring(0, tagNameStr.length()-1)+")";
				String tagIds = "";
				List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(tagSql);
				if(listMap!=null && listMap.size()>0){
					for(int i=0;i<listMap.size();i++){
						tagIds+="'"+StringUtil.toString(listMap.get(i).get("tag_id"))+"',";
					}
				}
				String activityIds = "";
				String activitySql = "select distinct t.activity_id from t_activity_tag  t where t.tag_id in("+tagIds.substring(0, tagIds.length()-1)+")";
				List<Map<String, Object>> listMap_videoId=this.jdbcTemplate.queryForList(activitySql);
				if(listMap_videoId!=null && listMap_videoId.size()>0){
					for(int i=0;i<listMap_videoId.size();i++){
						activityIds+="'"+StringUtil.toString(listMap_videoId.get(i).get("activity_id"))+"',";
					}
					sql.append(" and t.id in("+activityIds.substring(0, activityIds.length()-1)+")");
				}else{
					sql.append(" and t.id in('')");
				}
			}
			
			
			if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
				sql.append("  and t.create_time>='"+DateUtil.dateToString(this.updateDate(this.getDate(startTime), "start"))+"' and t.create_time<='"+DateUtil.dateToString(this.updateDate(this.getDate(endTime), "end"))+"'");
			} else if (StringUtils.isNotBlank(startTime)) {
				sql.append("  and t.create_time>='"+DateUtil.dateToString(this.updateDate(this.getDate(startTime), "start"))+"'");
			} else if (StringUtils.isNotBlank(endTime)) {
				sql.append("  and t.create_time<='"+DateUtil.dateToString(this.updateDate(this.getDate(endTime), "end"))+"'");
			}
			
			if(StringUtils.isNotBlank(status)){
				sql.append(" and t.status="+Integer.parseInt(status));
			}
			sql.append(" order by t.create_time desc");
			//System.out.println("****************"+sql.toString());
			tlist = (List<TActivity>) this.getListBySql(pager, sql.toString(),TActivity.class);
			//add by william 2014-12-11
			//List list = new ArrayList();
			for (int i = 0; i < tlist.size(); i++) {
				TActivity tActivity = tlist.get(i);
				Criteria activityImageCriteria = getCriteria(TActivityImage.class);
				activityImageCriteria.add(Restrictions.eq("activityId", tActivity.getId()));
				activityImageCriteria.addOrder(Order.asc("orderIndex"));
				tActivity.setImageList(activityImageCriteria.list());
				
				//add by Bing 2015-08-05
				String content = StringUtil.toStringNoTrim(tActivity.getDescription());
				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
					tActivity.setVideoFlag("video");
				}else{
					tActivity.setVideoFlag("notvideo");
				}
				
				//设置点赞数量   Add by Bing 2015-07-07
				String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
				if(listMapLike!=null && listMapLike.size()>0){
					tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
				}else{
					tActivity.setLikeAmount(0);
				}
				
				//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
				String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
				Integer amount=0;
				if(listMapIsLike!=null && listMapIsLike.size()>0){
					amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
				}else{
					amount=0;
				}
				if(amount>0){
					tActivity.setLike(true);
				}else{
					tActivity.setLike(false);
				}
				
				//设置浏览数量  Add by Bing 2015-07-07
				tActivity.setBrowseTimes(logService.getBrowseTimes(tActivity.getId(), "activity", userId));
				
				//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
				tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(tActivity.getId(), "activity", userId));
				
				
				//设置评论  Add by Bing 2015-07-07
//				List<TComments> commentList = new ArrayList<TComments>();
//				String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+tActivity.getId()+"' order by t.publish_time desc";
//				List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//				if(listMapComment!=null && listMapComment.size()>0){
//					for(int k=0;k<listMapComment.size();k++){
//						TComments comment=new TComments();
//						comment.setId(StringUtil.toString(listMapComment.get(k).get("id")));
//						String userid=StringUtil.toString(listMapComment.get(k).get("userId"));
//						comment.setUserId(userid);
//						
//						//Console Admin角色可以删除评论
//						if (listUser.getRole().indexOf("Console Admin") == -1) {
//							comment.setCanDelete(false);
//						}else{
//							comment.setCanDelete(true);
//						}
//						
//						comment.setUserName(StringUtil.toString(listMapComment.get(k).get("user_name")));
//						comment.setContentId(StringUtil.toString(listMapComment.get(k).get("contentId")));
//						comment.setComments(StringUtil.toString(listMapComment.get(k).get("comments")));
//						String pubDate = StringUtil.toString(listMapComment.get(k).get("publish_time"));
//						comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//						
//						commentList.add(comment);
//					}
//					tActivity.setCommentList(commentList);
//				}
//				
//				//设置评论数量  Add by Bing 2015-07-07
//				tActivity.setCommentAmount(commentList.size());
			}
			return tlist;
		}
	}

	/**
	 * pc
     * 正在进行中的活动
     * @author Bing  
	 * @times  2014-11-07
     * list
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object ongoing(String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		//用户是否登录，和是否有效
		TUser listUser = findEntity(TUser.class, userId);
		if (listUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		Criteria criteria = getCriteria(TActivity.class);
		//必须时发布状态的
		criteria.add(Restrictions.eq("status", 2));
        //输入的搜索条件
		/*Date thisDate=this.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
		criteria.add(Restrictions.and(
				//活动结素时间大于等于当前时间
				Restrictions.ge("endTime", thisDate),
				//并且活动开始时间小于等于当前时间
				Restrictions.le("startTime", thisDate)
				));*/
		criteria.addOrder(Order.asc("startTime"));
		
		List<TActivity> list = new ArrayList<TActivity>();
		
		List<TActivity> reslist = (List<TActivity>)listQBC(criteria);
		for (Iterator iterator = reslist.iterator(); iterator.hasNext();) {
			TActivity tActivity = (TActivity) iterator.next();
			//add by Bing 2015-08-05
			Set<TTags> tagset = tActivity.getTags();
			Iterator it=tagset.iterator();
			String haveNowTagFlag="noNowTag";
				
			while(it .hasNext() ){
				TTags tag=(TTags) it.next();
				if("NOW".equals(tag.getName())){
					haveNowTagFlag="haveNowTag";
					break;
				}
			}
			tActivity.setHaveNowTagFlag(haveNowTagFlag);

			//add by william 2014-12-11
			Criteria activityImageCriteria = getCriteria(TActivityImage.class);
			activityImageCriteria.add(Restrictions.eq("activityId", tActivity.getId()));
			activityImageCriteria.addOrder(Order.asc("orderIndex"));
			tActivity.setImageList(activityImageCriteria.list());
			
			tActivity.setFlag(this.checkActivity(tActivity.getId(), userId));
			
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tActivity.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tActivity.setLike(true);
			}else{
				tActivity.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			tActivity.setBrowseTimes(logService.getBrowseTimes(tActivity.getId(), "activity", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(tActivity.getId(), "activity", userId));
			
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+tActivity.getId()+"' order by t.publish_time desc";
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					
//					//Console Admin角色可以删除评论
//					if (listUser.getRole().indexOf("Console Admin") == -1) {
//						comment.setCanDelete(false);
//					}else{
//						comment.setCanDelete(true);
//					}
//					
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tActivity.setCommentList(commentList);
//			}
//			
//			//设置评论数量  Add by Bing 2015-07-07
//			tActivity.setCommentAmount(commentList.size());
			
			list.add(tActivity);
		}
		return list;
	}

	/**
	 * pc
     * 正在进行中的活动报名情况
     * @author Bing  
	 * @times  2014-11-07
     * list
     */
	@Override
	public Object ongoing_view(Pager pager,String activityId,String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		//用户是否登录，和是否有效
		TUser listUser = findEntity(TUser.class, userId);
		if (listUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		Criteria criteria = getCriteria(TActivityAppUser.class);
		
		criteria.createAlias("activity", "act");
		criteria.add(Restrictions.eq("act.id", activityId));
        
		criteria.addOrder(Order.desc("enroll_time"));
		return listPageQBCL(criteria, pager);
	}

//	/**
//	 * pc
//     * 导出某个活动的详细信息
//     * @author Bing  
//	 * @throws Exception 
//	 * @times  2014-11-07
//     * param:exportType    如果值为“excel”就导出excel，如果是“txt”就导出txt文件，默认导出txt文件
//     */
//	@Override
//	public boolean export(String exportType, String activityId,String userId,HttpServletRequest request, HttpServletResponse response) throws Exception {
//
//      
//		if(StringUtils.isBlank(activityId)){
//			return false;
//		}
//		if("txt".equals(exportType)||exportType==null||"".equals(exportType)){
//			StringBuffer  txt =new StringBuffer("");  //需要导出的数据内容
//			StringBuffer  t =new StringBuffer("");
//			TActivity activity = findEntity(TActivity.class, activityId);
//			if(activity==null){
//				throw new ValidateException("activity.activityUnExist");
//			}
//			//报名方式
//			String joinType=null;
//			if(activity.getJoinType()==null||"".equals(activity.getJoinType())){
//				activity.setJoinType(0);
//			}
//			if(activity.getJoinType()==0){
//				joinType="First come first participation";
//			}else{
//				joinType="Organized by the decision";
//			}
//			if(activity!=null){
//				//组装活动的数据
//				t.append("subject,startTime,endTime,venue,briefContent,description,limitNum,joinType,deadline,createUser,createTime,editUser,editTime,reviewUser,reviewTime");
//				String createUser=" ";
//				String editUser=" ";
//				String reviweUser=" ";
//				if(activity.getCreateUser()!=null){
//					createUser=activity.getCreateUser().getUserName();
//				}
//				if(activity.getEditUser()!=null){
//					editUser=activity.getEditUser().getUserName();
//				}
//				if(activity.getReviewUser()!=null){
//					reviweUser=activity.getReviewUser().getUserName();
//				}
//				txt.append("\r\n'"+activity.getSubject()+"',");
//				txt.append("'"+activity.getStartTime()+"',");
//				txt.append("'"+activity.getEndTime()+"',");
//				txt.append("'"+activity.getVenue()+"',");
//				txt.append("'"+activity.getBriefContent()+"',");
//				txt.append("'"+activity.getDescription()+"',");
//				txt.append("'"+activity.getLimitNum()+"',");
//				txt.append("'"+joinType+"',");
//				txt.append("'"+activity.getDeadline()+"',");
//				txt.append("'"+createUser+"',");
//				txt.append("'"+activity.getCreateTime()+"',");
//				txt.append("'"+editUser+"',");
//				txt.append("'"+activity.getEditTime()+"',");
//				txt.append("'"+reviweUser+"',");
//				txt.append("'"+activity.getReviewTime()+"'");
//				//组装把报名字段信息
//				String str=activity.getEnroll_need();
//				if(str!=null){
//					String[] strArr=str.split("==");
//					String[] param=null;
//					for(String  s:strArr){
//						if(s!=null){
//							param=s.split(":");
//							if(param.length==2){
//								t.append(","+param[0]);
//							}
//						}
//					}
//					t.append(",enroll_time\r\n");
//				}
//				Set<TActivityAppUser> app=activity.getAppUsers();
//				StringBuffer  txt2 =txt; 
//				for(TActivityAppUser ta:app){
//					StringBuffer  txt3 =txt2; 
//					t.append(txt3);
//					if(ta!=null){
//						String enroll_info=ta.getEnroll_info();
//						if(enroll_info!=null){
//							String[] strArr=enroll_info.split("==");
//							String[] param=null;
//							for(String  s:strArr){
//								if(s!=null){
//									param=s.split(":");
//									if(param.length==3){
//										t.append(",'"+param[2]+"'");
//									}
//								}
//							}
//							t.append(",'"+ta.getEnroll_time()+"'");
//						}
//					}
//				}
//			}
//			
//			//执行txt导出结素 end
//			if(this.exportTXT(response, t.toString())){
//				return true;
//			}else{
//				return false;
//			}
//		}
//		  return true;
//	}
	/**
	 * pc
     * 导出某个活动的报名信息
     * @author Bing  
	 * @throws Exception 
	 * @times  2015-8-28
     *
     */
	@Override
	public boolean export(String exportType, String activityId,String userId,HttpServletRequest request, HttpServletResponse response) throws Exception {

      
		if(StringUtils.isBlank(activityId)){
			return false;
		}
		if("csv".equals(exportType)||exportType==null||"".equals(exportType)){
			StringBuffer  title =new StringBuffer("");  //需要导出的数据标头
			StringBuffer  t =new StringBuffer("");//需要导出的数据
			TActivity activity = findEntity(TActivity.class, activityId);
			if(activity==null){
				throw new ValidateException("activity.activityUnExist");
			}
			
			if(activity!=null){
				//组装活动的数据
				Set<TActivityAppUser> app=activity.getAppUsers();
				for(TActivityAppUser ta:app){
					if(ta!=null){
						String enroll_info=ta.getEnroll_info();
						if(enroll_info!=null){
							String[] strArr=enroll_info.split("==");
							String[] param=null;
							for(int i=0;i<strArr.length;i++){
								String s = strArr[i];
								TUserApp tuserapp =null;
								if(s!=null){
									param=s.split(":");
									if(param.length==3){
										String key = param[0];
										String value = param[2];
										if(!title.toString().contains(key)){
											title.append(key+",");
										}
										t.append(value+",");
										if("Staff ID".equals(key)){
											tuserapp = findEntity(TUserApp.class, value);
											if(!title.toString().contains("Username,Email")){
												title.append("Username,Email,");
											}
											t.append(StringUtil.toString(tuserapp.getUserName())+","+StringUtil.toString(tuserapp.getEmail())+",");
										}
										
									}
								}
							}
							String registration_date = ta.getEnroll_time()+"";
							t.append(registration_date.substring(0, registration_date.length()-2)+"\n");
						}
					}
				}
			}
			
			if(!title.toString().contains("Registration date")){
				title.append("Registration date"+"\n");
			}
			
			//导出的整个数据
			StringBuffer dataStr = title.append(t);
			//执行csv导出
			if(this.exportCsv(response, dataStr.toString())){
				return true;
			}else{
				return false;
			}
		}
		  return true;
	}
	/**
	 * pc
     * 查询所有活动
     * @author Bing  
	 * @throws Exception 
	 * @times  2014-11-07
     * 只有AdminConsole可以使用
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object adminShow(Pager pager,String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("activity.unLogin");
		// 得到登录用户的信息
		TUser loginUser = findEntity(TUser.class, userId);

		if (loginUser == null) {
			throw new ValidateException("user.userUnExist");
		}

		if (loginUser.getRole().indexOf("Console Admin") == -1) {
			throw new ValidateException("user.userIsNotRole");
		}

		
		Criteria criteria = getCriteria(TActivity.class);

		criteria.addOrder(Order.desc("createTime"));

		List<TActivity> list = new ArrayList<TActivity>();
		
		List<TActivity> reslist = (List<TActivity>)listPageQBCL(criteria, pager);
		for (Iterator iterator = reslist.iterator(); iterator.hasNext();) {
			TActivity tActivity = (TActivity) iterator.next();
			//add by Bing 2015-08-05
			Set<TTags> tagset = tActivity.getTags();
			Iterator it=tagset.iterator();
			String haveNowTagFlag="noNowTag";
				
			while(it .hasNext() ){
				TTags tag=(TTags) it.next();
				if("NOW".equals(tag.getName())){
					haveNowTagFlag="haveNowTag";
					break;
				}
			}
			tActivity.setHaveNowTagFlag(haveNowTagFlag);
			//add by Bing 2015-08-05
			String content = StringUtil.toStringNoTrim(tActivity.getDescription());
			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
				tActivity.setVideoFlag("video");
			}else{
				tActivity.setVideoFlag("notvideo");
			}
			
			//add by william 2014-12-11
			Criteria activityImageCriteria = getCriteria(TActivityImage.class);
			activityImageCriteria.add(Restrictions.eq("activityId", tActivity.getId()));
			activityImageCriteria.addOrder(Order.asc("orderIndex"));
			tActivity.setImageList(activityImageCriteria.list());
			
			tActivity.setFlag(this.checkActivity(tActivity.getId(), userId));
			
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tActivity.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tActivity.setLike(true);
			}else{
				tActivity.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			tActivity.setBrowseTimes(logService.getBrowseTimes(tActivity.getId(), "activity", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(tActivity.getId(), "activity", userId));
			
			
			//设置评论  Add by Bing 2015-07-07
//			List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+tActivity.getId()+"' order by t.publish_time desc";
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					
//					//Console Admin角色可以删除评论
//					if (loginUser.getRole().indexOf("Console Admin") == -1) {
//						comment.setCanDelete(false);
//					}else{
//						comment.setCanDelete(true);
//					}
//					
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tActivity.setCommentList(commentList);
//			}
//			
//			//设置评论数量  Add by Bing 2015-07-07
//			tActivity.setCommentAmount(commentList.size());
			
			list.add(tActivity);
		}
		return list;
	}

	
	
	
	
	/**app端用户访问活动列表
	 * 
	 * (non-Javadoc)
	 * @see com.none.web.service.activity.IActivityService#show(com.none.core.model.Pager, java.lang.String, java.lang.String)
	 */
	@SuppressWarnings({ "unchecked", "rawtypes"})
	@Override
	public Object show(Pager pager, String keyword, String tagNames,String userId) throws Exception {
		// 分割tag标签
		String[] charSet = { ",", "，", "|", "｜", "/", "\\", "、" };
		// TUser listUser = findEntity(TUser.class, userId);

		Criteria criteria = getCriteria(TActivity.class);
		// criteria.add(Restrictions.eq("type", "news"));

		if (StringUtils.isNotBlank(keyword)) {
			criteria.add(Restrictions.or(Restrictions.like("subject", "%" + keyword + "%"),
					Restrictions.like("briefContent", "%" + keyword + "%")));
		}
		if (StringUtils.isNotBlank(tagNames)) {
			List<String> tagName = StringUtil.split(tagNames, charSet);
			Criteria tagCriteria = getCriteria(TTags.class);

			tagCriteria.add(Restrictions.in("name", tagName));
			List<TTags> tTagsList = tagCriteria.list();
			List<String> acyivityIds = new ArrayList<String>();
			for (TTags tTags : tTagsList) {
				for (TActivity activity : tTags.getActivitys()) {
					acyivityIds.add(activity.getId());
				}
			}
			if (acyivityIds.size() > 0) {
				criteria.add(Restrictions.in("id", acyivityIds));
			}else{
				return new ArrayList<TActivity>();
			}
		}

		criteria.add(Restrictions.eq("status", 2));
		criteria.addOrder(Order.desc("editTime"));
		
		List<TActivity> list = new ArrayList<TActivity>();
		
		List<TActivity> reslist = (List<TActivity>)listPageQBCL(criteria, pager);
		for (Iterator iterator = reslist.iterator(); iterator.hasNext();) {
			TActivity tActivity = (TActivity) iterator.next();
			//add by Bing 2015-08-04
			String content = StringUtil.toStringNoTrim(tActivity.getDescription());
			if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
				tActivity.setVideoFlag("video");
			}else{
				tActivity.setVideoFlag("notvideo");
			}

			//add by william 2014-12-11
			Criteria activityImageCriteria = getCriteria(TActivityImage.class);
			activityImageCriteria.add(Restrictions.eq("activityId", tActivity.getId()));
			activityImageCriteria.addOrder(Order.asc("orderIndex"));
			tActivity.setImageList(activityImageCriteria.list());
			
			tActivity.setFlag(this.checkActivity(tActivity.getId(), userId));
			
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				tActivity.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+tActivity.getId()+"' and t.userId='"+userId+"' and t.delete_flag='0'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				tActivity.setLike(true);
			}else{
				tActivity.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			tActivity.setBrowseTimes(logService.getBrowseTimes(tActivity.getId(), "activity", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(tActivity.getId(), "activity", userId));
			
			
			//设置评论  Add by Bing 2015-07-07
			//List<TComments> commentList = new ArrayList<TComments>();
//			String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+tActivity.getId()+"' order by t.publish_time desc";
//			List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//			if(listMapComment!=null && listMapComment.size()>0){
//				for(int i=0;i<listMapComment.size();i++){
//					TComments comment=new TComments();
//					comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//					String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//					comment.setUserId(userid);
//					//登录人可以删除自己的评论，不能删除其他人的
//					if(userid.equals(userId)){
//						comment.setCanDelete(true);
//					}else{
//						comment.setCanDelete(false);
//					}
//					comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//					comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//					comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//					String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//					comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//					
//					commentList.add(comment);
//				}
//				tActivity.setCommentList(commentList);
//			}
			
			//设置评论数量  Add by Bing 2015-07-07
			tActivity.setCommentAmount(commentsService.getCommentsAmount(tActivity.getId(), "activity"));
			
			list.add(tActivity);
		}
		return list;
	}
	
	/**
	 * check checkActivity add by william 2014-12-11
	 * @param activityId
	 * @param userId
	 * @return
	 */
	public String checkActivity(String activityId,String userId){
		String flag = "";
		//判断用户登录是否合法
		if (StringUtils.isBlank(userId)){
			flag = "activity.userIsNull";
			return flag;
		}
		TUserApp addUser = findEntity(TUserApp.class, userId);
		if (addUser == null) {
			flag = "user.userUnExist";
			return flag;
		}
		
		TActivity activity=findEntity(TActivity.class,activityId);
		if(activity==null){
			flag = "activity.activityUnExist";
			return flag;
		}
		//报名截止时间是否已经过了
		Timestamp deadTime = activity.getDeadline();
		if(deadTime!=null&&!"".equals(deadTime)){
			long thisTimes=new Date().getTime();
			if(thisTimes>deadTime.getTime()){
				flag = "activity.deadTime";
				return flag;
			}
		}
		//报名人数是否已经上限
		Criteria criteria =  getCriteria(TActivityAppUser.class);
		criteria.createAlias("activity", "act");
		criteria.add(Restrictions.eq("act.id", activityId));
		Object totalRowsObj = criteria.setProjection(Projections.rowCount()).uniqueResult();
		if(totalRowsObj!=null){
			long totalRows=Long.valueOf(totalRowsObj.toString());
			long limitMans=0;
			if(activity.getLimitNum()!=null&&!"".equals(activity.getLimitNum())){
				limitMans=activity.getLimitNum();
			}
			if(totalRows>=limitMans){
				flag = "activity.limitNum";
				return flag;
			}
		}
		//防止重复报名
		criteria.createAlias("appUser", "appuser");
		criteria.add(Restrictions.eq("appuser.userId", userId));
		Object userRows = criteria.setProjection(Projections.rowCount()).uniqueResult();
		if(userRows!=null){
		   long l=Long.valueOf(userRows.toString());
		   if(l>0){
			 flag = "activity.appIsTwo";
			 return flag;
		   }
		}
		
		return flag;
	}
	
	/**
	 * app端用户报名
	 *  Dave20141108
	 */
	public boolean joinActivity(TActivityAppUser app,String activityId,String userId)  throws Exception{
		//判断用户登录是否合法
		if (StringUtils.isBlank(userId)){
			throw new ValidateException("activity.userIsNull");
		}
		TUserApp addUser = findEntity(TUserApp.class, userId);
		if (addUser == null) {
			throw new ValidateException("user.userUnExist");
		}
		
		TActivity activity=findEntity(TActivity.class,activityId);
		if(activity==null){
			throw new ValidateException("activity.activityUnExist");
		}
		//报名截止时间是否已经过了
		Timestamp deadTime = activity.getDeadline();
		if(deadTime!=null&&!"".equals(deadTime)){
			long thisTimes=new Date().getTime();
			if(thisTimes>deadTime.getTime()){
				throw new ValidateException("activity.deadTime");
			}
		}
		//报名人数是否已经上限
		Criteria criteria =  getCriteria(TActivityAppUser.class);
		criteria.createAlias("activity", "act");
		criteria.add(Restrictions.eq("act.id", activityId));
		Object totalRowsObj = criteria.setProjection(Projections.rowCount()).uniqueResult();
		if(totalRowsObj!=null){
			long totalRows=Long.valueOf(totalRowsObj.toString());
			long limitMans=0;
			if(activity.getLimitNum()!=null&&!"".equals(activity.getLimitNum())){
				limitMans=activity.getLimitNum();
			}
			if(totalRows>=limitMans){
				throw new ValidateException("activity.limitNum");
			}
		}
		//防止重复报名
		criteria.createAlias("appUser", "appuser");
		criteria.add(Restrictions.eq("appuser.userId", userId));
		Object userRows = criteria.setProjection(Projections.rowCount()).uniqueResult();
		if(userRows!=null){
		   long l=Long.valueOf(userRows.toString());
		   if(l>0){
			 throw new ValidateException("activity.appIsTwo");
		   }
		}
		
		
		String join_info=app.getEnroll_info();
		//报名信息是否符合要求要求用户填写时不可以填写“＝”   “:”  “[]”     
		// join_info="Chinase name:yes:陈宾==English name:no:aday==age:no:[]==sex:yes:man";//临时模拟数据
		if(StringUtils.isBlank(join_info)){
			throw new ValidateException("activity.joinInfoIsNull");
		}
		//william modify 2014-12-7 .replace := to ===. reason:field value maybe empty. seems can be :=.
		String[] testStrArr=new String[]{"::","===","=:"};
		for(String str:testStrArr){
			if(join_info.indexOf(str)>=0){
				throw new ValidateException("activity.IllegalContent");
			}
		}
		String[] joinInfo_arr=join_info.split("==");
		for(String infoStr:joinInfo_arr){
			String[] strarr=infoStr.split(":");
			if(strarr!=null){
				//william modify 2014-12-7 .field value maybe empty. seems can 2
				if(strarr.length!=3&&strarr.length!=2){
					throw new ValidateException("activity.IllegalContent");
				}else{
					String isneed=strarr[1];
					if("yes".equals(isneed)){
						if(strarr.length==2){
							throw new ValidateException("activity.joinInfoIsNull");
						}else{
							String value = strarr[2];
							if("[]".equals(value)){
								throw new ValidateException("activity.joinInfoIsNull");
							}
						}
					}
				}
			}
		}
		
		
		
		
		app.setId(CreateID.getID());
		app.setEnroll_info(join_info);
		//关联app 用户
		TUserApp userApp=new TUserApp();
		userApp.setUserId(userId);
		app.setActivity(activity);
		app.setAppUser(userApp);
		//报名时间
		app.setEnroll_time(new Timestamp(new Date().getTime()));
		if (saveEntity(app) == null) {
			return false;
	    }
		return true;
	}
	/**
	 * 传递时间戳转换成日期型
	 * 
	 * @param unixDate
	 * @return
	 * @throws Exception
	 */
	private Date getDate(String unixDate) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long unixLong = 0;
		Date date = new Date();
		try {
			unixLong = Long.parseLong(unixDate) * 1000;
		} catch (Exception ex) {
			throw new ValidateException("news.requestDateError");
		}
		try {
			date = format.parse(format.format(unixLong));
		} catch (Exception ex) {
			throw new ValidateException("news.requestDateError");
		}
		return date;
	}
	
	/**
	 * 将日期的开始时间和结束时间重置
	 * @param date
	 * @param startOrEnd
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	private Date updateDate(Date date,String startOrEnd){
		if("start".equals(startOrEnd)){
			date.setHours(00);
			date.setMinutes(00);
			date.setSeconds(00);
		}else{
			date.setHours(23);
			date.setMinutes(59);
			date.setSeconds(59);
		}
		return date;
	}
	/**
	 * 传递dat转换成一定格式的date
	 * 
	 * @param unixDate
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private Date formatDate(Date date,String formatStr) throws Exception {
		if("".equals(formatStr)||formatStr==null){
			formatStr="yyyy-MM-dd HH:mm:ss";
		} 
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		return format.parse(format.format(date));
	}
	public static void main(String[] args){
	
		//System.out.print("==");
	}

	// 输出TXT  
	public boolean exportTXT(HttpServletResponse response,String str){  
	  
		response.setContentType("text/plain");// 一下两行关键的设置
		response.addHeader("Content-Disposition",
				"attachment;filename=Activity.txt");// filename指定默认的名字
		BufferedOutputStream buff = null;
		StringBuffer write = new StringBuffer();
		ServletOutputStream outSTr = null;
		try {
			outSTr = response.getOutputStream();// 建立
			buff = new BufferedOutputStream(outSTr);
			write.append(str);
			buff.write(write.toString().getBytes("UTF-8"));
			buff.flush();
		} catch (Exception e) {
			return false;
		} finally {
			if (buff != null) {
				try {
					buff.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outSTr != null) {
				try {
					outSTr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	    }
	
	
	// 输出TXT  
		public boolean exportCsv(HttpServletResponse response,String str){  
		  
			response.setContentType("text/plain");// 一下两行关键的设置
			response.addHeader("Content-Disposition",
					"attachment;filename=Activity.csv");// filename指定默认的名字
			BufferedOutputStream buff = null;
			StringBuffer write = new StringBuffer();
			ServletOutputStream outSTr = null;
			try {
				outSTr = response.getOutputStream();// 建立
				buff = new BufferedOutputStream(outSTr);
				write.append(str);
				buff.write(write.toString().getBytes("GBK"));
				buff.flush();
			} catch (Exception e) {
				return false;
			} finally {
				if (buff != null) {
					try {
						buff.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (outSTr != null) {
					try {
						outSTr.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return true;
		    }

		@SuppressWarnings("rawtypes")
		@Override
		public Object getActivityDetialInfo(String activityId, String type,
				String userId,String appOrPCFlag) throws Exception {
			if (StringUtils.isBlank(userId))
				throw new ValidateException("news.notIsLoginUser");
			TActivity tActivity=null;
			if(StringUtils.isNotBlank(activityId)){
				tActivity = findEntity(TActivity.class, activityId);
				if(tActivity==null){
					throw new ValidateException("activity.activityUnExist");
				}
				
				//add by Bing 2015-08-05
				Set<TTags> tagset = tActivity.getTags();
				Iterator it=tagset.iterator();
				String haveNowTagFlag="noNowTag";
					
				while(it .hasNext() ){
					TTags tag=(TTags) it.next();
					if("NOW".equals(tag.getName())){
						haveNowTagFlag="haveNowTag";
						break;
					}
				}
				tActivity.setHaveNowTagFlag(haveNowTagFlag);
				
				//add by Bing 2015-08-04
				String content = StringUtil.toStringNoTrim(tActivity.getDescription());
				if(content.contains(SysConstant.startString)&&content.contains(SysConstant.endString)){
					tActivity.setVideoFlag("video");
				}else{
					tActivity.setVideoFlag("notvideo");
				}
				
				//设置当前用户是否对该信息点过赞
				String islikeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+activityId+"' and t.userId='"+userId+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
				Integer amount=0;
				if(listMapIsLike!=null && listMapIsLike.size()>0){
					amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
				}else{
					amount=0;
				}
				if(amount>0){
					tActivity.setLike(true);
				}else{
					tActivity.setLike(false);
				}
				//设置点赞数量
				String likeSql="select count(t.id) num from t_like t where t.type='activity' and t.contentId='"+activityId+"' and t.delete_flag='0'";
				List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
				if(listMapLike!=null && listMapLike.size()>0){
					tActivity.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
				}else{
					tActivity.setLikeAmount(0);
				}
				//设置浏览数量
				tActivity.setBrowseTimes(logService.getBrowseTimes(activityId, "activity", userId));
				//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
				tActivity.setAllBrowseTimes(logService.getAllBrowseTimes(activityId, "activity", userId));
//				//设置评论
//				List<TComments> commentList = new ArrayList<TComments>();
//				String commentSql="select t.id,t.contentId,t.userId,tup.user_name,t.comments,t.publish_time from t_comments t ,t_user_app tup where t.userId=tup.user_id and t.type='activity' and t.contentId='"+activityId+"' order by t.publish_time desc";
//				List<Map<String, Object>> listMapComment=this.jdbcTemplate.queryForList(commentSql);
//				if(listMapComment!=null && listMapComment.size()>0){
//					for(int i=0;i<listMapComment.size();i++){
//						TComments comment=new TComments();
//						comment.setId(StringUtil.toString(listMapComment.get(i).get("id")));
//						String userid=StringUtil.toString(listMapComment.get(i).get("userId"));
//						comment.setUserId(userid);
//						//登录人可以删除自己的评论，不能删除其他人的
//						if(userid.equals(userId)){
//							comment.setCanDelete(true);
//						}else{
//							comment.setCanDelete(false);
//						}
//						comment.setUserName(StringUtil.toString(listMapComment.get(i).get("user_name")));
//						comment.setContentId(StringUtil.toString(listMapComment.get(i).get("contentId")));
//						comment.setComments(StringUtil.toString(listMapComment.get(i).get("comments")));
//						String pubDate = StringUtil.toString(listMapComment.get(i).get("publish_time"));
//						comment.setPubDate(pubDate.substring(0, pubDate.length()-2));
//						
//						commentList.add(comment);
//					}
//					tActivity.setCommentList(commentList);
//				}
				
				//设置评论数量
				if("PC".equals(appOrPCFlag)){
					tActivity.setCommentAmount(commentsService.getAllCommentsAmount(tActivity.getId(), "activity"));
				}else{
					tActivity.setCommentAmount(commentsService.getCommentsAmount(tActivity.getId(), "activity"));
				}
				
				//设置提交人名字
				if(StringUtils.isNotBlank(tActivity.getSubmit_user_id())){
					TUser submitUser = findEntity(TUser.class, tActivity.getSubmit_user_id());
					tActivity.setSubmit_user_name(submitUser.getUserName());
				}
			}else{
				throw new ValidateException("activity.activityUnExist");
			}
			return tActivity;
		}  
}
